import { createRouter, createWebHistory } from 'vue-router'
import { useSystemStore } from '@/stores/modules/system.js';
import front from '@/router/modules/front.js'
import backend from '@/router/modules/backend.js'
import personal from '@/router/modules/personal.js'
import { useAuthStore } from '@/stores/modules/auth.js';
import { ElMessage } from 'element-plus'

const routes = [
  /**前台 */
  {
    path: '/',
    name: 'root',
    component: () => import('@/components/layout/front/FrontLayout.vue'),
    children: front
  },
  /**后台 */
  {
    path: '/backend',
    name: 'backend',
    // redirect: '/backend/learn-collect',
    component: () => import('@/components/layout/backend/BackendLayout.vue'),
    children: backend
  },
  /**个人中心 */
  {
    path: '/personal-center',
    name: 'personal-center',
    // redirect: '/personal-center/publicize-setting',
    component: () => import('@/components/layout/personal-center/PersonalCenterLayout.vue'),
    children: personal
  },
  /**统一登录回调地址 */
  {
    path: '/auth',
    name: 'login-auth',
    component: () => import('@/views/system/auth.vue'),
  },
  {
    path: '/404',
    name: 'NotFound',
    meta: { hidden: true },
    component: () => import('@/views/system/NotFound.vue')
  },
  { path: '/:pathMatch(.*)*', name: 'NotMatch', redirect: '/', meta: { hidden: true } }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const systemStore = useSystemStore()
  systemStore.needFooter = true

  const authStore = useAuthStore()
  if (authStore.isExpired()) {
    // 过期清除登录信息
    authStore.cleanAuthInfo()
  }

  /**以下需要权限，过期跳转登录页面 */
  if (to.path.includes('/personal-center') || to.path.includes('/backend')) {
    if (authStore.isExpired()) return authStore.toLoginPage()
  }

  const allActions = authStore?.userInfo?.allActions || []
  if (to.path.includes("/backend") && to.path !== "/backend") {
    if (!allActions.find(item => item == to.meta.permissionId)) {
      const is = () => {
        ElMessage({
          type: 'warning',
          message: "暂未获取对应模块权限，无法进入",
          showClose: true,
          duration: 2000,
          onClose: () => {
            window.open(from.path, "_self")
          }
        })
      }
      return is()
    }
  }

  // 设置web标题
  document.title = to?.meta?.title
    ? `${to.meta.title} | ${import.meta.env.VITE_APP_WEB_TITLE}`
    : import.meta.env.VITE_APP_WEB_TITLE

  next()
})

export const SetupRouter = {
  install: (app) => {
    app.use(router)
  }
}

export default router
